package com.cg.springSecurity.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cg.springSecurity.base.ResultInfo;
import com.cg.springSecurity.exception.UsernameNotFoundException;
import com.cg.springSecurity.pojo.User;
import com.cg.springSecurity.service.UserService;
import com.cg.springSecurity.valid.AddGroup;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cg
 * @since 2022-05-11
 */
@RestController
//@Controller
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    //异步检查密码是否正确
    @PostMapping("check")
    public ResultInfo check(@RequestBody User user){
        User check = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (check == null){
            throw new UsernameNotFoundException();
        }else {
            String password = check.getPassword();
            //验证旧密码是否一致
            if (password.equals(user.getPassword())){
                return new ResultInfo<>( "密码验证成功");
            }else {
                return new ResultInfo<>("error" , "密码错误");
            }
        }
    }

    //获取用户邮箱
    @GetMapping("{username}")
    public ResultInfo getUserInfo(@PathVariable String username){
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (user == null){
            throw new UsernameNotFoundException();
        }
        user.setPassword("null");//清空密码
        return new ResultInfo<>(user);
    }
    //修改密码
    @PostMapping("update")
    public ResultInfo update(@RequestBody User user){
        userService.update(user , new QueryWrapper<User>().eq("username" , user.getUsername()));

        return new ResultInfo<>("密码修改成功");
    }

    //注册用户
    @PostMapping("regist")
    public ResultInfo regist(@Validated({AddGroup.class}) User user) {
//        System.out.println("user = " + user);
        //判断用户名是否已经存在
        if (!"null".equals(user.getUsername())) {
            //查看数据库中该用户名数据
            if (userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername())) != null) {
                return new ResultInfo<>( "error!", "用户名已经存在");
            }
        }
        if (!user.isEnabled()) user.setEnabled(true);
        userService.save(user);
        return new ResultInfo<>();
    }
    //登录
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password) {
        // login logic
        return "success";
    }
    //注销
    @ApiOperation(value = "Logout current user")
    @PostMapping("/logout")
    public void logout() {
        // logout logic
    }
}

